package com.mxchip.livestar.rest.log;

import android.os.Environment;

import com.mxchip.livestar.utils.MyLog;
import com.mxchip.livestar.rx.RxSchedulersHelper;
import com.mxchip.livestar.utils.ZipUtil;
import com.mxchip.livestar.base.SystemData;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class RetrofitFactory {
    private static RetrofitApi getRetrofitApi() {
        return OKHTTP.getInstance().create(RetrofitApi.class);
    }

    public static Observable<BaseBean> updateFile(String fileName, Boolean isPass) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        //在这里添加服务器除了文件之外的其他参数@Query("") String filename,
//                .addFormDataPart("filename", Utils.getUserId());
//                .addFormDataPart("参数2", "值2");
        String s = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;

        String zipPath = s.substring(0, s.lastIndexOf("/"));
        String zipName = s.substring(s.lastIndexOf("/"), s.lastIndexOf(".")) + ".zip";
        String srcPath = s.substring(0, s.lastIndexOf("/"));
        String srcName = s.substring(s.lastIndexOf("/"));
        MyLog.logD(MyLog.RETROFIT_FACTORY_MODEL,"RetrofitFactory::updateFile:"
                + " zipPath:" + zipPath
                + " zipName:" + zipName
                + " srcPath:" + srcPath
                + " srcName:" + srcName
        );

        File file = new File(zipPath + zipName);
        MyLog.logD(MyLog.RETROFIT_FACTORY_MODEL,"RetrofitFactory::updateFile:" + file.getAbsolutePath());
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        //添加文件(file是服务器中需要的文件参数)
        builder.addFormDataPart("file", file.getName(), imageBody);
        List<MultipartBody.Part> parts = builder.build().parts();
        String serverFileName = getServerFileName(fileName, isPass);
        return Observable.create((ObservableOnSubscribe<String>) emitter -> {
            ZipUtil.compressFile(zipPath, zipName, srcPath, srcName);
            emitter.onNext("...");
        })
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(s1 -> MyLog.logD(MyLog.RETROFIT_FACTORY_MODEL,"RetrofitFactory::accept: compress finish"))
                .observeOn(Schedulers.io())
                .flatMap(egisterResponse -> getRetrofitApi().upLoading(serverFileName, parts))
                .compose(RxSchedulersHelper.io_main()).compose(RxResultHelper.INSTANCE.handleResult());


    }

    private static String getServerFileName(String fileName, Boolean isPass) {
        String serverFileName;
        if (isPass) {
            String[] split = fileName.split("/");
            String passLogFile = split[split.length - 1];
            String[] passLogFileSplit = passLogFile.split("\\.");
            String suffix = passLogFileSplit[passLogFileSplit.length - 1];
            String dataSting = passLogFile.substring(0, passLogFile.length() - (suffix.length() + 1));
            serverFileName = SystemData.userId() + "_by_pass_" + dataSting;
        } else {
            serverFileName = SystemData.userId();
        }
        return serverFileName;
    }
}
